<template>
  <div class="edit-page-wrap edit-page-wrap-1">
    <Head title="方案信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
        >
          <el-form-item label="方案名称" prop="planName">
            <el-input
              v-model.trim="ruleForm.planName"
              placeholder="请输入方案名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="提供运营商" prop="orgId">
            <qc-select
              :value="ruleForm.orgId"
              :remote="true"
              :filterable="true"
              :options="optionsS.orgData"
              placeholder="请输入搜索关键词"
              @change="handleChangeOrg"
            >
            </qc-select>
          </el-form-item>
          <el-form-item label="二次定价类型" prop="secondaryPricingType">
            <el-radio-group
              v-model="ruleForm.secondaryPricingType"
              v-for="(item, index) in optionsS.secondaryPricingTypeData"
              :key="index"
              @change="changeCompanyType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="电费折扣"
            prop="chargeDiscount"
            v-if="ruleForm.secondaryPricingType == 1"
          >
            <el-input
              v-model.trim="ruleForm.chargeDiscount"
              maxlength="3"
              placeholder="请输入电费折扣"
              clearable
            >
              <template #append>%</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="服务费折扣"
            prop="serviceDiscount"
            class="has-tips"
            v-if="ruleForm.secondaryPricingType == 1"
          >
            <el-input
              v-model.trim="ruleForm.serviceDiscount"
              maxlength="3"
              placeholder="请输入服务费折扣"
              clearable
            >
              <template #append>%</template>
            </el-input>
            <div class="tip">
              <div class="icon"></div>
              折扣价格设置，即在运营商推送价格基础上进行打折，仅保留4位小数，其他舍弃。
              示例：电站推送价格为1.1291元/度，折扣为80%，计算后价格为0.90328元/度，该电站在平台的基础价格为0.9032元/度。
            </div>
          </el-form-item>
          <el-form-item
            label="电费调价"
            prop="chargeFixedDifference"
            v-if="ruleForm.secondaryPricingType == 2"
          >
            <el-input-number
              v-model="ruleForm.chargeFixedDifference"
              :precision="2"
              :step="0.01"
              controls-position="right"
            />
            <span style="margin-left: 8px">元/度 </span>
          </el-form-item>
          <el-form-item
            label="服务费调价"
            prop="serviceFixedDifference"
            class="has-tips"
            v-if="ruleForm.secondaryPricingType == 2"
          >
            <el-input-number
              v-model="ruleForm.serviceFixedDifference"
              :precision="2"
              :step="0.01"
              controls-position="right"
            />
            <span style="margin-left: 8px">元/度 </span>
            <div class="tip">
              <div class="icon"></div>
              固定差额设置，即在运营商推送价格基础上，每度上调、下调固定金额，精确到2位小数。
              示例：电站推送电费价格为1.1291元/度，设置调价+0.01每度，该电站在平台的基础电价为1.1391元/度。
            </div>
          </el-form-item>
          <el-form-item label="方案生效时间" prop="times">
            <div class="edit-date-wrap" v-if="id">
              {{ ruleForm.times[0] }} 至 {{ ruleForm.times[1] }}
            </div>
            <div class="edit-date-wrap" v-else>
              <el-date-picker
                v-model="ruleForm.times"
                popper-class="qc-date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>
  
  <script lang="ts" setup>
import { FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import {
  saveEntrancePlan,
  updateEntrancePlan,
  queryEntrancePlan,
} from '@/service/apis/docking';
import { queryAllFlow } from '@/service/apis/org';
import { queryDicByParent } from '@/service/apis/api';
import { IS_DECIMAL_2, IS_INT_0, IS_DECIMAL_2_1 } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;
const ruleFormRef = ref<FormInstance>();

const optionsS = reactive({
  orgData: [] as any,
  secondaryPricingTypeData: [] as any,
});

const disabledDate = (time: any) => {
  return time.getTime() < new Date(new Date().toLocaleDateString()).getTime();
};
const checkTime = (rule: any, value: any, callback: any) => {
  const endData = `${value[1]} 23:59:59`;
  if (new Date(endData).getTime() < new Date().getTime()) {
    callback(new Error('结束时间不能小于当前时间'));
  }
  callback();
};

let ruleForm: any = reactive({
  id: id,
  secondaryPricingType: '1',
  // orgId: '',
  orgId: [] as any,
  planName: '',
  chargeDiscount: 100,
  serviceDiscount: 100,
  chargeFixedDifference: '0.00',
  serviceFixedDifference: '0.00',
  times: [] as any,
});
const rules = reactive<FormRules>({
  planName: [{ required: true, message: '请输入方案名称', trigger: 'blur' }],
  orgId: [{ required: true, message: '请选择提供运营商', trigger: 'change' }],
  secondaryPricingType: [
    { required: true, message: '请选择二次定价类型', trigger: 'change' },
  ],
  chargeDiscount: [
    { required: true, message: '请输入电费折扣', trigger: 'blur' },
    {
      pattern: IS_INT_0,
      message: '请输入大于等于0的正整数',
      trigger: 'blur',
    },
  ],
  serviceDiscount: [
    { required: true, message: '请输入服务费折扣', trigger: 'blur' },
    {
      pattern: IS_INT_0,
      message: '请输入大于等于0的正整数',
      trigger: 'blur',
    },
  ],
  chargeFixedDifference: [
    { required: true, message: '请输入电费调价', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_2_1,
      message: '电费调价精确到2位小数',
      trigger: 'blur',
    },
  ],
  serviceFixedDifference: [
    { required: true, message: '请输入服务费调价', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_2_1,
      message: '服务费调价精确到2位小数',
      trigger: 'blur',
    },
  ],
  times: [
    {
      required: true,
      message: '请选择方案生效时间',
      trigger: ['blur', 'change'],
    },
    { validator: checkTime, trigger: ['blur', 'change'] },
  ],
});

const back = () => {
  router.go(-1);
};

queryDicByParent({
  listDtos: ['secondaryPricingType'],
}).then((res: any) => {
  optionsS.secondaryPricingTypeData = res.secondaryPricingType;
});

// 更改企业类型
const changeCompanyType = (e: any) => {
  console.log(e);
  ruleForm.type = e;
  getOrgs();
};
// 获取企业名称
const getOrgs = () => {
  queryAllFlow({
    // type: ruleForm.type,
    attr: '3',
  }).then((res: any) => {
    if (res) {
      optionsS.orgData = res.listMap;
    }
  });
};
const handleChangeOrg = async (e: any) => {
  ruleForm.orgId = e;
};
// 详情赋值
if (id) {
  queryEntrancePlan({ id }).then((res: any) => {
    if (res) {
      for (const key in ruleForm) {
        if (res[key]) {
          ruleForm[key] = res[key];
        }
      }
      console.log(ruleForm);

      ruleForm.times = [res.startTime, res.endTime];
    }
  });
}

getOrgs();

// 提交
const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  console.log(ruleForm);

  if (!ruleFormRef.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  const form = { ...ruleForm };
  form.startTime = ruleForm.times[0];
  form.endTime = ruleForm.times[1];
  console.log('form====', form);
  if (form.secondaryPricingType == 1) {
    delete form.chargeFixedDifference;
    delete form.serviceFixedDifference;
  } else if (form.secondaryPricingType == 2) {
    delete form.chargeDiscount;
    delete form.serviceDiscount;
  }
  const amount = form.chargeFixedDifference - form.serviceFixedDifference;
  const amount1 = form.serviceFixedDifference - form.chargeFixedDifference;
  if (amount > 1 || amount1 > 1) {
    ElMessageBox.confirm('您的站点调价差额超过1.00元，是否继续保存？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      if (id) {
        updateEntrancePlan(form).then((res: any) => {
          emit('clear-cache');
          back();
        });
      } else {
        saveEntrancePlan(form).then((res: any) => {
          emit('clear-cache');
          back();
        });
      }
    });
  } else {
    if (id) {
      updateEntrancePlan(form).then((res: any) => {
        emit('clear-cache');
        back();
      });
    } else {
      saveEntrancePlan(form).then((res: any) => {
        emit('clear-cache');
        back();
      });
    }
  }
};
</script>
<style lang="scss">
.edit-page-wrap-1 {
  .edit-form-wrap {
    .el-input-number {
      .el-input {
        .el-input__wrapper {
          width: 0 !important;
        }
      }
    }
  }
}
</style>
